<?php
/////////////////////////////////////////////////////////////////////////////
// 
//
// workflow_system
//
// workflow_copyright
// 
/////////////////////////////////////////////////////////////////////////////

/**
 * FILE_NAME : fileoperate.class.php   FILE_PATH : classes\libraries\fileoperate.class.php
 * ....关于文件操作
 *
 * @copyright workflow_system 
 * @author workflow Develop Team 
 * @package 
 * @subpackage 
 * @version Wed Aug 08 12:17:22 CST 2007
 */

class FileOperate {

	function download($file_name, $app = '')
	{
		if ($app == 'fangan')
		{
			$full_name = BasePath . '/project/fangan/' . $file_name;
		}

		$fsize = filesize($full_name);
		$ext = substr($file_name, strrpos($file_name, '.')+1);

		switch ($ext) { 
		      case "pdf": $ctype="application/pdf"; break; 
		      case "exe": $ctype="application/octet-stream"; break; 
		      case "zip": $ctype="application/zip"; break; 
		      case "doc": $ctype="application/msword"; break; 
		      case "xls": $ctype="application/vnd.ms-excel"; break; 
		      case "ppt": $ctype="application/vnd.ms-powerpoint"; break; 
		      case "gif": $ctype="image/gif"; break; 
		      case "png": $ctype="image/png"; break; 
		      case "jpeg": 
		      case "jpg": $ctype="image/jpg"; break; 
		      default: $ctype="application/force-download"; 
		    } 
		

		header("Pragma: public"); // required 
	    header("Expires: 0"); 
	    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
	    header("Cache-Control: private",false); // required for certain browsers 
	    header("Content-Type: $ctype"); 
	    header("Content-Disposition: attachment; filename=\"".basename($full_name)."\";" ); 
	    header("Content-Transfer-Encoding: binary"); 
	    header("Content-Length: ".$fsize); 
	    flush(); // this doesn't really matter.

		$fp = fopen($full_name, "r"); 
		while (!feof($fp))
		{
		    echo fread($fp, 65536); 
		    flush(); // this is essential for large downloads
		}  
		fclose($fp); 


	}
	
	/**
	 * 上传文件
	 *
	 * @param unknown_type $rs
	 * @return unknown
	 */
	function upload_file($rs)
	{
		$maxmum_filesize = 5 * 1024 * 1024;
		if (is_uploaded_file($rs['tmp_name']) === FALSE)
		{
			return array('code' => 'errer', 'msg' => '请通过正确的途径上传文件');
		}
		
		if ($rs['size'] > $maxmum_filesize)
		{
			return array('code' => 'errer', 'msg' => '上传文件不能大于5M');
		}
		
		if (preg_match("/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx){1}$/i", strrchr($rs['name'], '.'), $type) == FALSE)
		{
			return array('code' => 'errer', 'msg' => '只允许上传jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx类型文件');
		}

		$safe_file_name = md5($rs['tmp_name'] . time()) . $type[0];
		$safe_file = BasePath . '/project/fangan/' . $safe_file_name;
		
		if (move_uploaded_file($rs['tmp_name'], $safe_file) === FALSE)
		{
			return array('code' => 'errer', 'msg' => '上传失败');
		}
		
		return array('code' => 'success', 'msg' => '上传成功', 'safe_file_name' => $safe_file_name);
	}
	
	function del_file($file_name, $app)
	{
		if ($app == 'fangan')
		{
			$full_name = BasePath . '/project/fangan/' . $file_name;
		}
		
		@unlink($full_name);
		
		return true;
	}
	/**
	* Utility function to return a value from a named array or a specified default
	*/

	function mosGetParam( &$arr, $name, $def=null, $mask=0 ) {
		$return = null;
		if (isset( $arr[$name] )) {
			if (is_string( $arr[$name] )) {
				if (!($mask&_MOS_NOTRIM)) {
					$arr[$name] = trim( $arr[$name] );
				}
				if (!($mask&_MOS_ALLOWHTML)) {
					$arr[$name] = strip_tags( $arr[$name] );
				}
				if (!get_magic_quotes_gpc()) {
					$arr[$name] = addslashes( $arr[$name] );
				}
			}
			return $arr[$name];
		} else {
			return $def;
		}
	}

	function mosMakePassword($length) {
		$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$len = strlen($salt);
		$makepass="";
		mt_srand(10000000*(double)microtime());
		for ($i = 0; $i < $length; $i++)
		$makepass .= $salt[mt_rand(0,$len - 1)];
		return $makepass;
	}

	/**
	* Chmods files and directories recursivel to given permissions
	* @param path The starting file or directory (no trailing slash)
	* @param filemode Integer value to chmod files. NULL = dont chmod files.
	* @param dirmode Integer value to chmod directories. NULL = dont chmod directories.
	* @return TRUE=all succeeded FALSE=one or more chmods failed
	*/
	function mosChmodRecursive($path, $filemode=NULL, $dirmode=NULL)
	{
		$ret = TRUE;
		if (is_dir($path)) {
			$dh = opendir($path);
			while ($file = readdir($dh)) {
				if ($file != '.' && $file != '..') {
					$fullpath = $path.'/'.$file;
					if (is_dir($fullpath)) {
						if (!mosChmodRecursive($fullpath, $filemode, $dirmode))
						$ret = FALSE;
					} else {
						if (isset($filemode))
						if (!@chmod($fullpath, $filemode))
						$ret = FALSE;
					} // if
				} // if
			} // while
			closedir($dh);
			if (isset($dirmode))
			if (!@chmod($path, $dirmode))
			$ret = FALSE;
		} else {
			if (isset($filemode))
			$ret = @chmod($path, $filemode);
		} // if
		return $ret;
	} // mosChmodRecursive

	/**
     * 设置目录权限
     * @author workflow Develop Team     
     * @param  string $fileName
     * @param  string $type
     * @return bool
     */
	function WriteDirOrFile($fileName,$type){
		
		if (is_dir($fileName)){
			if (@is_writable($fileName)){
				return true;
			}else {
				return false;
			}
		}else{
			if ($type == 'dir'){
				if (!@mkdir($fileName,0755)){
					return false;
				}
			}
			if ($type=='file' && @filesize($fileName)==0){
				$handle = @fopen ($fileName, "wb");
				@fclose ($handle);
			}
			if ($type=='emptyfile'){
				$handle = @fopen ($fileName, "wb");
				@fclose ($handle);
			}
			if (!@is_writable($fileName)){
				return false;
			}
		}
		
		return true;
	}


	/**
     * 删除文件夹目录
     * @author workflow Develop Team     
     * @param  string $dir
     * @return bool
     */
	function fullRmdir( $dir ){
		if ( !is_writable( $dir ) ){
			if ( !@chmod( $dir, 0775 ) ){
				return FALSE;
			}
		}

		$d = dir( $dir );
		while ( FALSE !== ( $entry = $d->read() ) )
		{
			if ( $entry == '.' || $entry == '..' ){
				continue;
			}
			$entry = $dir . '/' . $entry;
			if ( is_dir( $entry ) )	{
				if ( !$this->fullRmdir( $entry ) )	{
					return FALSE;
				}
				continue;
			}
			if ( !@unlink( $entry ) ){
				$d->close();
				return FALSE;
			}
		}
		$d->close();
		@rmdir( $dir );
		return TRUE;
	}


	/**
     * 删除文件夹目录下的文件
     * @author workflow Develop Team     
     * @param  string
     * @return bool
     */
	function DelDirfile($dir){

		$dh  = opendir($dir);
		while (false !== ($filename = readdir($dh))) {
			$files[] = $filename;
		}

		array_shift ($files);
		array_shift ($files);
		$templates_c = array();
		foreach ($files as $k=>$v){

			if ( $v!='.' && $v!='..' ) {
				if (!is_dir($dir."/".$v)){
					//$templates_c[] = $v ;
					unlink($dir."/".$v);
				}
			}
		}
	}

	/**
     * 建立过滤文件
     * @author workflow Develop Team     
     * @param  $file string $filter_array array()
     * @return mixed
     */
	function makeFilterFile($file,$filter_array){
		$currentTime = date('Y-m-d : h:i ',time());
		$line  = "<?php\n";
		$line .= "//ShopNC ini filter file \n//Created: $currentTime \n\n";
		$line .= " \$_filterstringCacheArray = array( \n";
		$line .= " 'filter' => array ( \n";
		$line .= "  \n";
		/*敏感词*/
		$line .= "  'patterns' => \n";
		$line .= "  	array ( \n";
		if (is_array($filter_array["patterns"])){
			$i = 0;
			foreach ($filter_array["patterns"] as $k => $v){
				if ($v != ""){
					$line .= "  $i => '". $v ."',\n";
					$i++;
				}
			}
		}
		$line .= "  	), \n";
		/*替换*/
		$line .= "  'replacements' => \n";
		$line .= "  	array ( \n";
		if (is_array($filter_array["replacements"])){
			$i = 0;
			foreach ($filter_array["replacements"] as $k => $v){
				if ($v != ""){
					$line .= "  $i => '". $v ."',\n";
					$i++;
				}
			}
		}
		$line .= "  	), \n";
		$line .= "	\n ),";
		$line .= " \n );\n\n";
		$line .= "//End";
		$line .= " \n?>";

		$report = FileOperate::writeFile($file,$line);
		return $report;
	}

	/**
	 * 建立商品类别文件
	 * @author workflow Develop Team    
	 * @param  
	 * @return int/bool/object/array
	 */
	function makeProductClassFlie($string,$createfile){		
		$currentTime = date('Y-m-d : h:i ',time());
		$file_string = "";
		$file_string  = "<?php\n";
		$file_string .= "//ShopNC ProductClass  file \n//Created: $currentTime \n\n";				
		$file_string .= "\$node_cache = array( \n";
		$file_string .= $string;
		$file_string .= "\n );";
		$file_string .= "\n?>";
		$report = FileOperate::writeFile($createfile,$file_string);
		return $report;
	}

	/**
	 * 建立地区的js文件
	 * @author workflow Develop Team    
	 * @param  
	 * @return int/bool/object/array
	 */
	function makeAreaJsFlie($parent_string,$sun_string,$creatfile){
		$currentTime = date('Y-m-d : h:i ',time());
		$file_string .=<<<EOF
//ShopNC area js file
//Created: $currentTime
var province;
var city = new Array();
$parent_string
$sun_string
var ifshowcode = 0;
var selectprovince = "";
var selectcity = "";

function iniProvince(ProvinceObj){
	ProvinceObj.length = province.length;
	for (i = 0; i < province.length; i++) {
		if (i==0)
			ProvinceObj.options[i].value = '';
		else
			ProvinceObj.options[i].value = province[i][0];
		ProvinceObj.options[i].text  = province[i][0];
		if (selectprovince==province[i][0]){
			ProvinceObj.selectedIndex = i;
		}
	}
	//ProvinceObj.selectedIndex = 0;
	

}

function iniCity(ProvinceObj,CityObj){
	var a = new Array();
	a = city[ProvinceObj.selectedIndex];
	CityObj.length = a.length;
	CityObj.selectedIndex = 0;
	for (i = 0; i < a.length; i++) {
		if (i==0)
			CityObj.options[i].value = '';
		else
			CityObj.options[i].value = a[i][0];
		CityObj.options[i].text  = a[i][0];
		if (selectcity==a[i][0]){
			CityObj.selectedIndex = i;
		}
	}

}

EOF;
			return FileOperate::writeFile($creatfile,$file_string);
	}




	/**
     * 建立文件
     * @author workflow Develop Team     
     * @param  $file string $resource mixed
     * @return mixed
     */
	function writeFile($file,$resource){
		if ( $fh = @fopen( $file, 'wb+' ) )
		{
			@fwrite($fh, $resource);
			@fclose($fh);
			@chmod ($file,0777);
			return true;
		}else{
			$error_report = "please confirm $file have write permissions!";
			return $error_report;
		}
	}

	/**
	 * 列出文件夹目录
	 * @author workflow Develop Team    
	 * @param  
	 * @return array
	 */
	function listDir($path){
		if (is_dir($path)) {
			$dh = @opendir($path);
			While(false !==($flist=@readdir($dh))){
				if ($flist != '.' && $flist != '..'){
					$array = array();
					$array['name'] = $flist;
					if (is_file($path.'/'.$flist)){
						$array['type'] = "file";
					}
					if(is_dir($path.'/'.$flist)){
						$array['type'] = "dir";
					}
					$file_array[] = $array;
					unset($array);
				}
			}
			return $file_array;
		}else {
			return false;
		}		
	}
	
	/**
	 * 生成频道参数文件
	 * @author workflow Develop Team    
	 * @param  $file_name 文件名，$resource 文件内容
	 * @return bool
	 */
	function makeChannelParamFile($file_name,$resource){
		$file_string  = "<?php\n";
		$file_string .= " \$ChannelParamArray = array( \n";
		$file_string .= $resource;
		$file_string .= " \n );\n\n";
		$file_string .= " \n?>";
		return FileOperate::writeFile($file_name,$file_string);
	}
	
	/**
	 * 建立地区文件
	 * @author workflow Develop Team    
	 * @param  
	 * @return int/bool/object/array
	 */
	function makeAreaFlie($string,$createfile){		
		$currentTime  = date('Y-m-d : h:i ',time());
		$file_string  = "";
		$file_string  = "<?php\n";
		$file_string .= "//ShopNC Area  file \n//Created: $currentTime \n";	
		$file_string .= "//array('area_id','area_parent_id','area_name','area_sort','depth')\n\n";
		$file_string .= "\$area_cache = array( \n";
		$file_string .= $string;
		$file_string .= "\n );";
		$file_string .= "\n?>";
		$report = FileOperate::writeFile($createfile,$file_string);
		return $report;
	}
	
	/**
	 * 建立商品品牌文件
	 * @author workflow Develop Team    
	 * @param  
	 * @return int/bool/object/array
	 */
	function makeProductBrandFlie($string,$createfile){		
		$currentTime  = date('Y-m-d : h:i ',time());
		$file_string  = "";
		$file_string  = "<?php\n";
		$file_string .= "//ShopNC Product Brand  file \n//Created: $currentTime \n";	
		$file_string .= "//array('pb_id','pb_u_id','pb_name','pb_sort','pb_deeppath')\n\n";
		$file_string .= "\$product_brand_cache = array( \n";
		$file_string .= $string;
		$file_string .= "\n );";
		$file_string .= "\n?>";
		$report = FileOperate::writeFile($createfile,$file_string);
		return $report;
	}
	
}
?>